<template>
  <div class="user">
    <PageSearch
      :searchFormConfig="searchFormConfig"
      @resetBtnClick="handleResetClick"
      @queryBtnClick="handleQueryClick"
    />
    <div class="content">
      <PageContent
        ref="pageContentRef"
        :contentTableConfig="contentTableConfig"
        pageName="users"
        @newBtnClick="handleNewData"
        @editBtnClick="handleEditData"
        @look-btn-click="handleLookData"
      />
      <PageModal
        :modalConfig="modalConfigRef"
        ref="pageModalRef"
        :defaultInfo="defaultInfo"
        pageName="users"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import PageSearch from '@/components/page-search/index'
import PageContent from '@/components/page-content/index'
import PageModal from '@/components/page-modal'
import { searchFormConfig } from './config/pageSearch.config'
import { contentTableConfig } from './config/pageContent.config'
import { modalConfig } from './config/pageModal.config'
import { useModal } from '@/hooks/useModal'
import { usePageSearch } from '@/hooks/usePageSearch'
import { useStore } from '@/store'
import { computed } from 'vue'

const [handleResetClick, handleQueryClick, pageContentRef] = usePageSearch()

/**
 * newCallback 新建按钮的一些特有逻辑
 */
const newCallback = () => {
  const passwordItem = modalConfig.formItems.find(
    (item) => item.field === 'password'
  )
  passwordItem!.isHidden = false
}
/**
 * editCallback 编辑按钮的一些特有逻辑，此处隐藏密码框
 */
const editCallback = () => {
  const passwordItem = modalConfig.formItems.find(
    (item) => item.field === 'password'
  )
  passwordItem!.isHidden = true
}
// 动态添加部门角色列表
/**
 * modalConfigRef 动态modalConfig
 * 此处使用computed 是因为获取角色和部门列表是异步的，所以当最开始加载到此处时，并没有数据，所以使用动态computed，在其内部需要返回modalConfig
 */
const store = useStore()
const modalConfigRef = computed(() => {
  const departmentItem = modalConfig.formItems.find(
    (item) => item.field === 'departmentId'
  )
  departmentItem!.options = store.state.departmentList.map((item) => {
    return { title: item.name, value: item.id }
  })
  const roleItem = modalConfig.formItems.find((item) => item.field === 'roleId')
  roleItem!.options = store.state.roleList.map((item) => {
    return { title: item.name, value: item.id }
  })
  return modalConfig
})

// 调用hooks公共的方法
const [
  handleNewData,
  handleEditData,
  handleLookData,
  defaultInfo,
  pageModalRef
] = useModal(modalConfig, newCallback, editCallback)
</script>

<style scoped lang="less">
.content {
  margin-top: 20px;
  padding: 20px;
  background-color: #ffffff;
}
</style>
